/**
 * Copyright (c) Software Institute of PKU
 * All rights reserved. 
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */
package edu.pku.sei.modeler.model.core;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.ui.views.properties.IPropertySource;
import org.w3c.dom.Element;

import edu.pku.sei.gefcommon.descriptor.core.PropertyDescriptorAdapter;
import edu.pku.sei.modeler.exceptions.FactoryNotFoundException;
import edu.pku.sei.modeler.model.common.AbstractFactory;
import edu.pku.sei.modeler.model.common.MetaTypedList;
import edu.pku.sei.modeler.model.common.ModelRegistry;
import edu.pku.sei.modeler.model.xml.XMLUtility;
/**
 * @author zl
 *
 */
public class MetaModelElement extends MetaElement implements IAdaptable{
	protected MetaTypedList comments;
	
	public MetaModelElement() {
		super();
	}
	
//	@ListProperty(
//			ID = "MODELELEMENT_COMMENTS",
//			Catalog = "Model",
//			Name = CorePackage.MODELELEMENT_COMMENTS,
//			ElementType = CorePackage.__METACOMMENT__
//			)
	public MetaTypedList getComments() {
		if(comments == null) {
			comments = new MetaTypedList(MetaComment.class, this, CorePackage.MODELELEMENT_COMMENTS);
		}
		return comments;
	}
	
	public void serialize(Element root) {
		super.serialize(root);
		XMLUtility.xmlInstance.serializeNodes(root, CorePackage.MODELELEMENT_COMMENTS, comments);
	}
	
	public void deSerialize(Element root) {
		super.deSerialize(root);
		this.getComments().addAll(XMLUtility.xmlInstance.deSerializeNodes(root, CorePackage.MODELELEMENT_COMMENTS));
	}
	public void dynamicSet(String featureID, Object value) {
		super.dynamicSet(featureID, value);
	}
	
	public MetaModelElement newInstance(String typeStr) {
		try {
			AbstractFactory factory = ModelRegistry.getRegistry().getFactory(model);
			Object obj = factory.createElement(typeStr, true);
			if(obj != null) {
				((MetaModelElement)obj).setModel(model);
				return (MetaModelElement)obj;
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (FactoryNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	protected EClass eStaticClass() {
		return EMetaModelPackage.Literals.EMETA_MODEL_ELEMENT;
	}
	
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case EMetaModelPackage.EMETA_MODEL_ELEMENT__COMMENTS:
				return getComments();
		}
		return super.eGet(featureID, resolve, coreType);
	}
	
	public Object getAdapter(Class adapter) {
		if (IPropertySource.class == adapter) {
			return new PropertyDescriptorAdapter(this);
		}
		return null;
	}

}
